import { getAuthToken } from '@/utils/auth';
import { message } from 'antd';
import * as API from '@/services';
import queryString from 'query-string';

const triggerDownload = (url: string) => {
  const a = document.createElement('a');
  a.href = url;
  a.target = '_blank';
  document.body.appendChild(a);
  a.click();
  // 清理资源
  document.body.removeChild(a);
};

const processError = (e: any) => {
  if (e.response.status === 404) {
    message.error('PDF文件不存在');
    return;
  } else if (e.status === 402) {
    message.error('您未订阅指定的刊期');
    return;
  } else if (e.response?.data?.msg) {
    message.error(e.response?.data?.msg);
  } else {
    message.error('下载失败');
  }
};

export const downloadJournalPeriodPdf = async (period?: API.JournalPeriod) => {
  try {
    if (!period) {
      return;
    }
    const resp = await API.preCheckJournalPeriodDownload(period.id, { skipErrorHandler: true });
    if (resp.flag) {
      const journalName = (`《${period.journal.journalNameCn}》` || period.journal.journalNickname || '').replace(/\s/g, '_');
      const fname = `${journalName}${period?.year}_${period?.volume}(${period?.period}).pdf`;
      const searchString = queryString.stringify({
        authToken: getAuthToken(),
        fname,
      });
      const url = `${REQUEST_BASE_URL}/api/v1/front/journal-period/${period?.id}/pdf?${searchString}`;
      triggerDownload(url);
    }
  } catch (e: any) {
    processError(e);
  }
};

export const downloadJournalPeriodZip = async (period?: API.JournalPeriod) => {
  if (!period) {
    return;
  }
  const journalName = (`《${period.journal.journalNameCn}》` || period.journal.journalNickname || '').replace(/\s/g, '_');
  const fname = `${journalName}${period?.year}_${period?.volume}(${period?.period}).zip`;
  const searchString = queryString.stringify({
    authToken: getAuthToken(),
    fname,
  });
  const url = `${REQUEST_BASE_URL}/api/v1/front/journal-period/${period?.id}/zip?${searchString}`;
  triggerDownload(url);
};

export const downloadArticlePdf = async (article?: API.Article) => {
  try {
    if (!article) {
      return;
    }
    const resp = await API.preCheckArticleDownload(article.id, { skipErrorHandler: true });
    if (resp.flag) {
      const fname = `${article?.articleDoi}.pdf`;
      const searchString = queryString.stringify({
        authToken: getAuthToken(),
        fname,
      });
      const url = `${REQUEST_BASE_URL}/api/v1/front/article/${article?.id}/pdf?${searchString}`;
      triggerDownload(url);
    }
  } catch (e: any) {
    processError(e);
  }
};
